package cn.tedu.knows.portal.security;

import cn.tedu.knows.portal.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
//启动Spring-security的权限管理功能
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //配置类要继承
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在我们用户登录时,会自动调用userDetailsService中的方法获得
        //用户详情,这个详情会由Spring-Security框架获得,以进行后续判断
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()//禁用防跨域攻击功能
                .authorizeRequests()
                .antMatchers(
                        "/css/*",
                        "/js/*",
                        "/img/**",
                        "/bower_components/**",
                        "/login.html",
                        "/register.html",
                        "/register"
                ).permitAll()//上面设置的路径全部放行(不登录也能访问)
                .anyRequest()//其它请求
                .authenticated()//需要登录才能访问
                .and()//是一个分割
                .formLogin()
                .loginPage("/login.html")//配置登录页面使用login.html
                .loginProcessingUrl("/login")//处理登录请求的路径
                .failureUrl("/login.html?error")//登录失败显示错误信息,留在登录页
                .and()
                .logout()   //开始设置登出
                .logoutUrl("/logout")  //只要在访问的路径是/logout就触发登出
                .logoutSuccessUrl("/login.html?logout"); //登录后返回登录页
    }
}
